package sea.simulate;

import java.io.File;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import sea.util.PublicParam;
import sea.util.WinHelper;

/**
 *
 * This class builds the layout of Save interface
 * 
 * @author  Zhirun Ding
 * 
 * Created on 05/07/2012
 * 
 */

public class SimulateSaveForm extends javax.swing.JDialog {
    
    /** Creates new form SimuldateSaveForm */
    public SimulateSaveForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        chooseButton.setVisible(false);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        saveTypeButtonGroup = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        varList = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        fileNameText = new javax.swing.JTextField();
        trasectoryRadioButton = new javax.swing.JRadioButton();
        statisticsRadioButton = new javax.swing.JRadioButton();
        backButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        chooseButton = new javax.swing.JButton();
        helpButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sea.SimHyAGui.class).getContext().getResourceMap(SimulateSaveForm.class);
        setTitle(resourceMap.getString("SimulateSaveForm.title")); // NOI18N
        setName("SimulateSaveForm"); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        varList.setName("varList"); // NOI18N
        varList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                varListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(varList);

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        fileNameText.setText(resourceMap.getString("fileNameText.text")); // NOI18N
        fileNameText.setName("fileNameText"); // NOI18N

        saveTypeButtonGroup.add(trasectoryRadioButton);
        trasectoryRadioButton.setSelected(true);
        trasectoryRadioButton.setText(resourceMap.getString("trasectoryRadioButton.text")); // NOI18N
        trasectoryRadioButton.setName("trasectoryRadioButton"); // NOI18N

        saveTypeButtonGroup.add(statisticsRadioButton);
        statisticsRadioButton.setText(resourceMap.getString("statisticsRadioButton.text")); // NOI18N
        statisticsRadioButton.setName("statisticsRadioButton"); // NOI18N

        backButton.setText(resourceMap.getString("backButton.text")); // NOI18N
        backButton.setName("backButton"); // NOI18N
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        nextButton.setText(resourceMap.getString("nextButton.text")); // NOI18N
        nextButton.setName("nextButton"); // NOI18N
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        chooseButton.setText(resourceMap.getString("chooseButton.text")); // NOI18N
        chooseButton.setName("chooseButton"); // NOI18N
        chooseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chooseButtonActionPerformed(evt);
            }
        });

        helpButton.setText(resourceMap.getString("helpButton.text")); // NOI18N
        helpButton.setName("helpButton"); // NOI18N
        helpButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(31, 31, 31)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(statisticsRadioButton)
                                    .addComponent(trasectoryRadioButton)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(36, 36, 36)
                                        .addComponent(chooseButton))
                                    .addComponent(fileNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(41, 41, 41)
                                .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(4, 4, 4)
                                .addComponent(helpButton))))
                    .addComponent(jLabel1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(60, 60, 60)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(chooseButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fileNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                        .addComponent(trasectoryRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(statisticsRadioButton)
                        .addGap(83, 83, 83))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(23, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(255, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(backButton)
                    .addComponent(nextButton)
                    .addComponent(helpButton))
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        this.isInitData = true;
        this.dispose();
    }//GEN-LAST:event_backButtonActionPerformed

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        //check data
        if (varList.getSelectedIndex() == -1) {
            JOptionPane.showMessageDialog(this, "please select a output data variable!", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        //file name
        if (fileNameText.getText().length() == 0) {
            JOptionPane.showMessageDialog(this, "please input file name!", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        //generate command of save
        toSaveCommand();
        
        //forward to next form
        this.isInitData = false;
        PublicParam.PreviousForm = this;
        if (trasectoryRadioButton.isSelected()) {
            WinHelper.showDialog(PublicParam.SimulateSTrasectoryForm, SimulateSTrajectoryForm.class);
        } else {
            WinHelper.showDialog(PublicParam.SimulateSStatisticsForm, SimulateSStatisticsForm.class);
        }        
    }//GEN-LAST:event_nextButtonActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        if (isInitData) {
            ArrayList<String> vars = PublicParam.SimHyACommand.getListOfDataVariables();
            WinHelper.initListbox2(varList, vars);
            //set default select index=0
            if (varList.getModel().getSize() > 0) {
                varList.setSelectedIndex(0);
                //fire event of mouse click event of varlist
                varListMouseClicked(null);
            }                                   
        }
    }//GEN-LAST:event_formComponentShown

    private void chooseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseButtonActionPerformed
        //show dialog for setting working direcotry
        JFileChooser c = new JFileChooser();
        c.setFileSelectionMode(JFileChooser.SAVE_DIALOG);
        c.setDialogTitle("input save file name");
        //c.setFileFilter(new TxtFilter());
        
        //set default direcotry
        c.setCurrentDirectory(new File(System.getProperty("user.dir")));
         
        int result = c.showSaveDialog(this);
        //System.out.println(1111);
        //System.out.println(result);
        if (result == JFileChooser.APPROVE_OPTION) {
            //System.out.println(2222);
            String path = c.getSelectedFile().getAbsolutePath();
            //System.out.println(path);
            File file = new File(path);
            if(file.exists()){
                JOptionPane.showConfirmDialog(this, file + "The file already exists, do you overwrite?", "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            }
            //save file
            fileNameText.setText(path);
        }
    }//GEN-LAST:event_chooseButtonActionPerformed

    private void helpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpButtonActionPerformed
        WinHelper.showHelp("save/save");
    }//GEN-LAST:event_helpButtonActionPerformed

    private void varListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_varListMouseClicked
        if (varList.getSelectedValue() != null) {
            //In the save gui, you should check if the data contains trajectory data
            //or statistics about trajectory and disable the corresponding options if not!
            //STATISTICS should be enabled only for data containing statistics. Check with appropriate Commander method
            String datavar = varList.getSelectedValue().toString();
            //Statistics
            if (PublicParam.SimHyACommand.isStatisticsExploratorVariable(datavar)
                    || PublicParam.SimHyACommand.trajectoryVariableContainsStatistics(datavar)
                    || PublicParam.SimHyACommand.exploratorVariableContainsFinalStateStatistics(datavar)) {
                statisticsRadioButton.setEnabled(true);
                statisticsRadioButton.setSelected(true);
            } else {
                statisticsRadioButton.setEnabled(false);
                trasectoryRadioButton.setSelected(true);
            }
            
            //trajectory
            if (PublicParam.SimHyACommand.isTrajectoryDataVariable(datavar)
                    || PublicParam.SimHyACommand.trajectoryVariableContainsTrajectoryData(datavar)
                    || PublicParam.SimHyACommand.exploratorVariableContainsTrajectoryData(datavar)) {
                trasectoryRadioButton.setEnabled(true);
                trasectoryRadioButton.setSelected(true);
            } else {
                trasectoryRadioButton.setEnabled(false);
                statisticsRadioButton.setSelected(true);
            }
        }
    }//GEN-LAST:event_varListMouseClicked
    
    public void toSaveCommand() {
        String s = "";
        s = "save($" + varList.getSelectedValue().toString() + ","
                + "file=" + fileNameText.getText() ;
        //PublicParam.CommandTypeName = "save";
        PublicParam.SimHyACommandExpression = s;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SimulateSaveForm dialog = new SimulateSaveForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton;
    private javax.swing.JButton chooseButton;
    private javax.swing.JTextField fileNameText;
    private javax.swing.JButton helpButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton nextButton;
    private javax.swing.ButtonGroup saveTypeButtonGroup;
    private javax.swing.JRadioButton statisticsRadioButton;
    private javax.swing.JRadioButton trasectoryRadioButton;
    private javax.swing.JList varList;
    // End of variables declaration//GEN-END:variables
    
    boolean isInitData = true;//init listbox before show
}
